package cn.tedu._08security.base.config;

import cn.tedu._08security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
//激活鉴权功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig {
    //创建UserDetailsService对象，放到IoC容器中，用于调用loadUserByUsername()方法
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
    // /api/public/hello  不需要认证
    // /api/private/hello 需要认证
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                // 设置/api/public/hello  不需要认证
                .requestMatchers("/api/public/**").permitAll()
                // 其他的请求需要认证
                .anyRequest().authenticated())
                .formLogin(from -> from
                        //表单登录相关的请求不需要认证
                        .permitAll ());
    return http.build();
    }
}
